package plc

import "strconv"

type Tag struct {
	Addr  string `json:"a"`
	Typ   string `json:"t"`
	Code  string
	DbNo  int
	Start int
	MBit  int
	Size  int
}
type TagGroup struct {
	Addr   string
	DbNo   int
	Start  int
	End    int
	Length int
	Elems  []*Tag
}

type TagBucket struct {
	Groups map[string]*TagGroup
	Keys   []string
	Data   map[string]string
}

func (b *TagBucket) Append(tag *Tag) {
	if _, ok := b.Data[tag.Code]; ok {
		return
	}
	b.Keys = append(b.Keys, tag.Code)
	b.Data[tag.Code] = tag.Code
	area := tag.Addr + strconv.Itoa(tag.DbNo)
	if _, ok := b.Groups[area]; !ok {
		b.Groups[area] = &TagGroup{
			Addr:   tag.Addr,
			DbNo:   tag.DbNo,
			Start:  -1,
			End:    0,
			Length: 0,
			Elems:  make([]*Tag, 0),
		}
	}
	if b.Groups[area].Start < 0 || tag.Start < b.Groups[area].Start {
		b.Groups[area].Start = tag.Start
	}
	thisEnd := tag.Start + tag.Size
	if thisEnd > b.Groups[area].End {
		b.Groups[area].End = thisEnd
	}
	b.Groups[area].Length = b.Groups[area].End - b.Groups[area].Start
	b.Groups[area].Elems = append(b.Groups[area].Elems, tag)
}

func NewTagBucket() *TagBucket {
	return &TagBucket{
		Groups: make(map[string]*TagGroup),
		Keys:   make([]string, 0),
		Data:   make(map[string]string),
	}
}
